package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.main.adapter.ContactsAdapter;
import com.netease.nim.demo.main.fragment.MainTabFragment;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.TeamMessageActivity;
import com.netease.nim.demo.session.model.MsgListItem;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.ImageAttachment;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw10000152.R;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import logic.bean.ContactInfo;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.FileUtil;
import logic.util.Utils;


public class ContactGroupActivity
        extends
        BaseBusinessActivity
{
	private Context			context;
							
	/** 页面类型 : 1为客户经理，2为普通用户 */
	private int				pageType	   = 1;
	private ListView		contactsListView;
	private List<Object>	items = new ArrayList<>();
	private ContactsAdapter	mAdapter;
	private View			emptyBg;
							
	private View			notifyBar;
							
	private TextView		tvTitle;
	private Button			btnBack, btnCreateTeam;
							
	private boolean			msgLoaded	   = false;
	private boolean			isMangerLoadOk = true;
	private boolean			isTeamLoadOk   = false;
	public static int		currentPosition;
	private Handler			handler		   = new Handler();
										   
	private String			fromType;
	private MsgListItem		selectedItem   = null;
	private File			file		   = null;
	private String			teamId		   = "";
	private TextView		tvCreateTeam;
	private Handler			myHandler	   = new Handler()
	                                       {
		                                       @Override
		                                       public void handleMessage(Message msg) {
			                                       super.handleMessage(msg);
			                                       //			                                           Bundle bundle = msg.getData();
			                                       switch (msg.what) {
				                                       case 1:
					                                       //															   String accId = bundle.getString("id");
					                                       IMMessage message = MessageBuilder.createImageMessage(teamId, SessionTypeEnum.Team, file, null);
					                                       NIMClient.getService(MsgService.class).sendMessage(message, false);
					                                       Toast.makeText(context, "转发成功", Toast.LENGTH_LONG).show();
					                                       break;
				                                       case -1:
					                                       Toast.makeText(context, "转发失败", Toast.LENGTH_LONG).show();
				                                       default:
					                                       break;
			                                       }
		                                       }
		                                       
	                                       };
										   
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_i_contacts_frament);
		context = this;
		fromType = getIntent().getStringExtra("fromType");
		selectedItem = (MsgListItem) getIntent().getSerializableExtra("message");
		initViews();
		setListeners();
		getPageType();
		//		getContactsList();
		requestContacts(false);
		initContactsList();
		registerObservers(true);
	}
	
	private void registerObservers(boolean register) {
		registerTeamUpdateObserver(register);
	}
	
	/**
	 * 注册群信息&群成员更新监听
	 */
	private void registerTeamUpdateObserver(boolean register) {
		if (register)
		{
			TeamDataCache.getInstance().registerTeamDataChangedObserver(teamDataChangedObserver);
		}
		else
		{
			TeamDataCache.getInstance().unregisterTeamDataChangedObserver(teamDataChangedObserver);
		}
	}
	
	TeamDataCache.TeamDataChangedObserver teamDataChangedObserver = new TeamDataCache.TeamDataChangedObserver()
	{
		
		@Override
		public void onUpdateTeams(List<Team> teams) {
		}
		
		@Override
		public void onRemoveTeam(Team team) {
			//TODO  解散群
			for (Object item : items)
			{
				if (item instanceof Team)
				{
					Team temp = (Team) item;
					if (TextUtils.equals(temp.getId(), team.getId()))
					{
						items.remove(item);
						mAdapter.notifyDataSetChanged();
						break;
					}
				}
			}
		}
	};
	
	private void initViews() {
		tvCreateTeam = (TextView) findViewById(R.id.common_header_create_team);
		contactsListView = (ListView) findViewById(R.id.new_i_contacts_lv);
		notifyBar = findViewById(R.id.status_notify_bar);
		emptyBg = findViewById(R.id.new_i_contacts_empty_rlay);
		notifyBar.setVisibility(View.GONE);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setText("群组");
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		btnCreateTeam = (Button) findViewById(R.id.common_header_commit);
		tvCreateTeam.setText("创建");
		tvCreateTeam.setVisibility(View.VISIBLE);
	}
	
	private void setListeners() {
		tvCreateTeam.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v) {
				//创建群组
				Intent creatTeamIntent = new Intent(ContactGroupActivity.this, NewInteractionCreateTeamChMActivity.class);
				creatTeamIntent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_CREATE_TEAM);
				startActivityForResult(creatTeamIntent, MainTabFragment.CREATE_TEAM);
			}
		});
		btnBack.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	/**
	 * 加载群列表
	 */
	//	private void getContactsList() {
	//		if (pageType == 0)
	//		{
	//			requestContacts(false);
	//			//			emptyBg.setVisibility(View.VISIBLE);
	//		}
	//		else if (pageType == 1)
	//		{
	//			requestContacts(false);
	//		}
	//		else if (pageType == 2)
	//		{
	//			//			if (null == Const.contactInfo) getUserManger();
	//			requestContacts(false);
	//		}
	//		
	//	}
	
	private void initContactsList() {
		
		mAdapter = new ContactsAdapter(this, items);
		contactsListView.setAdapter(mAdapter);
		contactsListView.setItemsCanFocus(true);
		contactsListView.setOnItemClickListener(new OnItemClickListener()
		{
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				currentPosition = position;
				Object obj = parent.getAdapter().getItem(position);
				talkto(obj);
			}
		});
		
	}
	
	private void requestContacts(boolean delay) {
		
		getHandler().postDelayed(new Runnable()
		{
			
			@Override
			public void run() {
				NIMClient.getService(TeamService.class).queryTeamList().setCallback(new RequestCallback<List<Team>>()
				{
					
					@Override
					public void onException(Throwable arg0) {
						Logger.e(arg0);
						isTeamLoadOk = false;
					}
					
					@Override
					public void onFailed(int arg0) {
						Logger.i("failed");
						isTeamLoadOk = true;
					}
					
					@Override
					public void onSuccess(List<Team> arg0) {
						Logger.d("success");
						isTeamLoadOk = true;
						if (items != null && items.size() > 0)
		                                                       items.clear();
						if (arg0 != null)
						{
							items.addAll(arg0);
							if (null != Const.contactInfo)
		                                                   items.add(0, Const.contactInfo);
						}
						notifyDataSetChanged();
						//						if (pageType == 2 && isMangerLoadOk)
						//						{
						//						}
						//						else if (pageType == 1)
						//						{
						//							notifyDataSetChanged();
						//						}
					}
				});
			}
		}, delay ? 250 : 0);
		
	}
	
	private Handler getHandler() {
		return handler;
	}
	
	private void postRunnable(final Runnable runnable) {
		handler.post(new Runnable()
		{
			@Override
			public void run() {
				// validate
				// TODO use getActivity ?
				//				if (!isAdded()) { return; }
				
				// run
				runnable.run();
			}
		});
	}
	
	private void postDelayed(final Runnable runnable, long delay) {
		handler.postDelayed(new Runnable()
		{
			@Override
			public void run() {
				// validate
				// TODO use getActivity ?
				//				if (!isAdded()) { return; }
				
				// run
				runnable.run();
			}
		}, delay);
	}
	
	private void notifyDataSetChanged() {
		
		boolean empty = items.isEmpty();
		emptyBg.setVisibility(empty ? View.VISIBLE : View.GONE);
		mAdapter.notifyDataSetChanged();
	}
	
	private void getPageType() {
		if (Const.UserRole.equals("0"))
		{
			pageType = 0;
		}
		else if (Const.UserRole.equals("1"))
		{
			pageType = 1;
		}
		else if (Const.UserRole.equals("2"))
		{
			pageType = 2;
		}
	}
	
	/**
	 * 获取客户的客户经理信息
	 */
	private void getUserManger() {
		ActionHelp.qryMyBoss(context, new GetUserMangerHandler());
	}
	
	class GetUserMangerHandler
	        extends
	        ObjectHttpResponseHandler<ContactInfo>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			isMangerLoadOk = false;
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, ContactInfo object, String responseString) {
			isMangerLoadOk = true;
			if (object != null)
			{
				items.add(0, object);
				Const.contactInfo = object;
				if (isTeamLoadOk)
				                  notifyDataSetChanged();
			}
		}
		
		@Override
		public Type getType() {
			return new TypeToken<ContactInfo>()
			{
			}.getType();
		}
		
	}
	
	/**
	 * 跳转到聊天页面
	 *
	 * @param item
	 */
	protected void talkto(Object item) {
		if (item instanceof ContactInfo)
		{
			ContactInfo info = (ContactInfo) item;
			String str;
			if (Utils.isEmpty(info.getNickName()))
			{
				str = info.getAccount();
			}
			else
			{
				str = info.getNickName();
			}
			//			Intent intent = new Intent();
			//			intent.putExtra(DefaultConsts.TO_P2P_PAGE_TAG, DefaultConsts.TO_P2P_PAGE_FROM_CONTACT_MANGER);
			//			intent.putExtra(DefaultConsts.TO_P2P_PAGE_INFO, str);
			//			P2PMessageActivity.start(getActivity(), info.getAccId(), intent);
			P2PMessageActivity.start(this, info.getAccId(), str);
			//			startActivity(new Intent(getActivity(), P2PMessageActivity.class));
		}
		else if (item instanceof Team)
		{
			Team team = (Team) item;
			if (fromType.equals("forward"))
			{
				ImageAttachment attachment = (ImageAttachment) selectedItem.getMessage().getAttachment();
				if (Utils.isNotEmpty(attachment.getUrl()))
				{
					file = downUrlTxt(attachment.getUrl(), FileUtil.ImageSavePath());
				}
				else
				{
					file = downUrlTxt(attachment.getPath(), FileUtil.ImageSavePath());
				}
				teamId = team.getId();
				finish();
			}
			else
			{
				TeamMessageActivity.start(this, team.getId());
			}
		}
		
	}
	
	public File downUrlTxt(final String fileUrl, String downPath) {
		final File savePath = new File(downPath);
		
		if (!savePath.exists())
		{
			savePath.mkdir();
		}
		String[] urlname = fileUrl.split("/");
		int len = urlname.length - 1;
		final String uname = urlname[len];//获取文件名  
		final File file1 = new File(savePath + "/" + uname + ".png");//创建新文件  ;
		new Thread()
		{
			@Override
			public void run() {
				try
				{
					//					file = new File(savePath + "/" + uname + ".png");//创建新文件  
					if (file1 != null && !file1.exists())
					{
						file1.createNewFile();
					}
					OutputStream oputstream = new FileOutputStream(file1);
					URL url = new URL(fileUrl);
					HttpURLConnection uc = (HttpURLConnection) url.openConnection();
					uc.setRequestMethod("GET");
					uc.setConnectTimeout(5 * 1000);
					uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true  
					uc.connect();
					InputStream iputstream = uc.getInputStream();
					//			System.out.println("file size is:" + uc.getContentLength());//打印文件长度  
					byte[] buffer = new byte[4 * 1024];
					int byteRead = -1;
					while ((byteRead = (iputstream.read(buffer))) != -1)
					{
						oputstream.write(buffer, 0, byteRead);
					}
					oputstream.flush();
					iputstream.close();
					oputstream.close();
					Message msg = Message.obtain();
					msg.what = 1;
					myHandler.sendMessage(msg);
				}
				catch (Exception e)
				{
					System.out.println("读取失败！");
					Message msg = Message.obtain();
					msg.what = -1;
					myHandler.sendMessage(msg);
					e.printStackTrace();
				}
			}
		}.start();
		
		return file1;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		registerObservers(false);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		requestContacts(false);
	}
	
	@Override
	public Handler getUIHandler() {
		// TODO Auto-generated method stub
		return null;
	}
}
